/*
    BibleNotebook - A bible reader software
    Copyright (C) 2014  Williams Fernando Lopez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
 */

package com.simplebible.dictionary;

import com.simplebible.dictionary.objects.DictDefinition;
import com.simplebible.dictionary.objects.NodeIndex;
import java.io.IOException;
import java.util.List;
import wl.util.TextResourcesUtil;
import wl.util.Utils;
import com.simplebible.objects.Preferences;

/**
 *
 * @author Williams Lopez
 */
public class DictionaryHTMLRenderer {

    public static String getDictionaryFountWords(String word,String dictionaryExpanded,boolean setWordInLabel) throws Exception{
        List<IDictionary> dicts = DictionaryUtils.getDictionaries();
        if(dicts==null || dicts.isEmpty()){
            throw new Exception(TextResourcesUtil.getText("no_hay_diccionarios"));
        }

        StringBuilder html = new StringBuilder();
        html.append("<html>\n");
        html.append("<head></head>\n");
        html.append("<body>\n");
        html.append("<p><font size='6' color='green' face='Arial'>");
        html.append(word);
        html.append("</font></p>");

        int countFounds = 0;

        html.append("<start/>");
        StringBuilder tmp = new StringBuilder();
        for(IDictionary d: dicts){
            try{

                tmp.delete(0, tmp.length());

                String header = "<div align='justify' style='width:100%;padding:5px;background-color:lightgray;border-style:solid;border-color:green;border-width:$px'><font size='3' color='gray' face='Arial'>"+d.getDictionaryName()+"</font><br>";

                DictDefinition def= d.get(word);
                if(def!=null){

                    countFounds++;

                    if(dictionaryExpanded!=null && dictionaryExpanded.equalsIgnoreCase(d.getDictionaryId())){
                        tmp.append(header.replace('$', '2'));
                        tmp.append(convertDefToHtml(d.getDictionaryId()+"&"+word,def, false));
                    }else{
                        tmp.append(header.replace('$', '1'));
                        tmp.append(convertDefToHtml(d.getDictionaryId()+"&"+word, def, true));
                    }

                    tmp.append("<br>");
                    if(def.getReferences()!=null){
                        for(String s: def.getReferences()){
                            tmp.append("<font size='3'  face='Arial' color='lightgray'>");
                            tmp.append(s);
                            tmp.append(" - ");
                            tmp.append("</font>");
                        }
                    }
                    tmp.append("</div><br/>");

//                    if(dictionaryExpanded!=null && dictionaryExpanded.equalsIgnoreCase(d.getDictionaryId())){
//                        html.insert(html.indexOf("<start/>"), tmp);
//                    }else{
                        html.insert(html.indexOf("<start/>")+8, tmp);
//                    }


                }else{
                    List<String> similars = d.listSimilarWords(word);
                    if(similars!=null && !similars.isEmpty()){
                        tmp.append(header.replace('$', '1'));
                        tmp.append("<font size='3'  face='Arial' color='red'>");
                        tmp.append(TextResourcesUtil.getText("no_existe_en_el_diccionario"));
                        tmp.append("</font>");
                        tmp.append("<br>");
                        tmp.append("<font size='3'  face='Arial'>");
                        tmp.append(TextResourcesUtil.getText("palabras_similares"));
                        tmp.append(": ");
                        tmp.append("</font>");
                        int count = 0;
                        for(String ps: similars){
                            tmp.append("<a href='similar:");
                            tmp.append(dictionaryExpanded);
                            tmp.append("&");
                            tmp.append(ps);
                            tmp.append("'>");
                            tmp.append("<font size='3'  face='Arial'>");
                            tmp.append(ps);
                            tmp.append("</font>");
                            tmp.append("</a>");
                            tmp.append(" ");
                            count++;
                            if(count>15) break;
                        }
                        tmp.append("</div><br/>");
                        html.append(tmp);
                    }
                }

            }catch(Exception e){
                Utils.printToLog("Error al buscar la definicion de "+word+" en el diccionario "+d.getDictionaryName(), e, Preferences.LOG_LEVEL_ERROR);
            }
        }

        if(countFounds==0){
            html.append("<p>");
            html.append("<font color='red' face='Arial' size='4'>");
            html.append(TextResourcesUtil.getText("palabra_no_existe_en_diccionarios"));
            html.append("</font>");
            html.append("</p>");
        }

        html.append("</body>\n");
        html.append("</html>\n");
        return html.toString();
    }

    private static String convertDefToHtml(String id, DictDefinition def, boolean shortDesc) {

        StringBuilder html = new StringBuilder();

        if (def.getDefinitions() != null) {


            if (shortDesc) {
                if(def.getDefinitions().length==0){
                    html.append("<font size='2'  face='Arial'>");
                    html.append(TextResourcesUtil.getText("ninguna_definicion"));
                    html.append("</font>");
                }else if(def.getDefinitions().length==1){
                    //html.append("<div align='justify'>");
                    html.append("<font size='3'  face='Arial'>");
                    String text = def.getDefinitions()[0].replaceAll("\\<.*?>","");
                    text = text.replaceAll("\\n", " ");
                    text =Utils.substring(text, 0, 150);
                    html.append(text);
                    html.append("...</font>");
                    html.append("<br>");
                    html.append("<a href='moretext:");
                    html.append(id);
                    html.append("'>");
                    html.append("<font size='3'  face='Arial' color='green'>");
                    html.append(TextResourcesUtil.getText("leer"));
                    html.append("</font>");
                    html.append("</a>");
                   // html.append("</div>");
                }else if(def.getDefinitions().length>1){
                    //html.append("<div align='justify'>");
                    html.append("<font size='3'  face='Arial'>");
                    String text = def.getDefinitions()[0].replaceAll("\\<.*?>","");
                    text = text.replaceAll("\\n", " ");
                    text =Utils.substring(text, 0, 150);
                    html.append(text);
                    html.append("</font>");
                    html.append("<br>");
                    html.append("<a href='moretext:");
                    html.append(id);
                    html.append("'>");
                    html.append("<font size='3'  face='Arial' color='green'>");
                    html.append(TextResourcesUtil.getText("leer"));
                    html.append(" ");
                    html.append(def.getDefinitions().length);
                    html.append(" ");
                    html.append(TextResourcesUtil.getText("definiciones"));
                    html.append("</font>");
                    html.append("</a>");
                    //html.append("</div>");
                }

            } else {

                int count = 0;
                html.append("<table border='0'>");
                for (String s : def.getDefinitions()) {
                    html.append("<tr>");
                    html.append("<td valign='top'><b>");
                    html.append((count + 1));
                    html.append(". ");
                    html.append("</b></td>");
                    html.append("<td>");


                    html.append("<div align='justify'>");
                    html.append("<font size='3'  face='Arial'>");
                    s= s.replaceAll("\\n", "<br>");
                    html.append(s);
                    html.append("</font>");

                    html.append("</div>");


                    html.append("<td>");
                    html.append("</tr>");
                    count++;
                }

                html.append("<tr><td></td><td>");
                html.append("<a href='lesstext:");
                html.append(id);
                html.append("'>");
                html.append("<font size='3'  face='Arial' color='green'>");
                html.append(TextResourcesUtil.getText("ocultar"));
                html.append("</font>");
                html.append("</a>");
                html.append("</td></tr>");


                html.append("</table>");
            }
        }


        return html.toString();
    }

    public static String getDictionaryMenu(String dictid, String key) throws IOException{
        IDictionary dict = DictionaryUtils.getDictionaryById(dictid);
        StringBuilder html = new StringBuilder();
        html.append("<html>\n");
        html.append("<head></head>\n");
        html.append("<body>\n");
        try {
            html.append("<p>");
            html.append("<font size='4' color='gray' face='Arial'><b>");
            html.append(dict.getDictionaryName());
            html.append("</b></font><br>");
            if (dict.getDictionaryUrl() != null) {
                html.append("<font size='2' color='lightgray' face='Arial'>");
                html.append(dict.getDictionaryUrl());
                html.append("</font><br>");
            }
            html.append(dict.getAllWords().size());
            html.append(" ");
            html.append(TextResourcesUtil.getText("definiciones"));
            html.append("</p>");


            NodeIndex index = null;

//            if(key==null || key.trim().equals("null")){
//                index = dict.getIndex();
//            }else{
//                index = dict.getIndex().findNodeByKey(key);
//            }

            index = dict.getIndex();
             
            if(index==null) throw new Exception("Cant create dictionary index");

            html.append("<p>");



            if (index.getChildren() != null) {
                for (NodeIndex n : index.getChildren()) {
                    html.append("<a style='text-decoration:none' href='");
                    html.append("dictkey:");
                    html.append(dictid);
                    html.append("&");
                    html.append(n.getValue());
                    html.append("&0'>");
                    html.append("<font color='black' face='Arial' size='5'>");
                    html.append(" ");
                    html.append(n.getValue());
                    html.append("</font>");
                    html.append("</a>");
                }
            }

  
            html.append("</p>");

            html.append("<div><font color='gray' size='3' face='Arial'>");
            html.append(dict.getDictionaryDescription().replaceAll("[\\\\]par", "\n"));
            html.append("</font><div>");



        } catch (Exception e) {
            Utils.printToLog("Error al mostrar el diccionario: " + dictid, e, Preferences.LOG_LEVEL_ERROR);
        }

        html.append("</body>\n");
        html.append("</html>\n");
        return html.toString();
    }

    public static String getDictionaryMenuForKey(String dictid,String key,int page) throws IOException{
        IDictionary dict = DictionaryUtils.getDictionaryById(dictid);
        StringBuilder html = new StringBuilder();
        html.append("<html>\n");
        html.append("<head></head>\n");
        html.append("<body>\n");
        try {
            html.append("<p>");
            html.append("<font size='4' color='gray' face='Arial'><b>");
            html.append(dict.getDictionaryName());
            html.append("</b></font><br>");
            if (dict.getDictionaryUrl() != null) {
                html.append("<font size='2' color='lightgray' face='Arial'>");
                html.append(dict.getDictionaryUrl());
                html.append("</font><br>");
            }


//            HashMap<String,List<String>> dir = new HashMap<String, List<String>>();
            List<String> words = null;
            NodeIndex index = dict.getIndex().findNodeByKey(key);
            words = index.getWords();

            if(words==null){
                words = dict.getAllWords();
            }

            int pageSize = 150;

            html.append(words.size());
            html.append(" ");
            html.append(TextResourcesUtil.getText("definiciones"));
            html.append("</p>");

            html.append("<p>");

            int pages = words.size()/pageSize;

            if(words.size()%pageSize>0){
                pages++;
            }

            if (pages > 1) {

                int prev = (page-1)<0?0:page-1;
                int next = (page+1)>pages?pages:page+1;

                html.append("<a style='text-decoration:none' href='");
                html.append("dictkey:");
                html.append(dictid);
                html.append("&");
                html.append(key);
                html.append("&");
                html.append(prev);
                html.append("'>");
                html.append("<font color='black' face='Arial' size='5'>");
                html.append("&lt;");
                html.append("</font>");
                html.append("</a>&nbsp;&nbsp;");


                for(int i=0;i< pages;i++){
                    String color = "gray";
                    if(page == i){
                        color = "red";
                    }
                    html.append("<a style='text-decoration:none' href='");
                    html.append("dictkey:");
                    html.append(dictid);
                    html.append("&");
                    html.append(key);
                    html.append("&");
                    html.append(i);
                    html.append("'>");
                    html.append("<font color='"+color+"' face='Arial' size='3'>");
                    html.append(i+1);
                    html.append("</font>");
                    html.append("</a>&nbsp;");
                }

                html.append("&nbsp;<a style='text-decoration:none;font-size:10px' href='");
                html.append("dictkey:");
                html.append(dictid);
                html.append("&");
                html.append(key);
                html.append("&");
                html.append(next);
                html.append("'>");
                html.append("<font color='black' face='Arial' size='5'>");
                html.append("&gt;");
                html.append("</font>");
                html.append("</a>&nbsp;");

            }
            html.append("<br/>");

            for(int i=page*pageSize;(i<((page+1)*pageSize))&& i < words.size();i++){
                String k = words.get(i);
                html.append("<a style='text-decoration:none' href='");
                html.append("similar:");
                html.append(dictid);
                html.append("&");
                html.append(k);
                html.append("'>");
                html.append(i+1);
                html.append(") ");
                html.append(k);
                html.append("</a><br/>");
            }

            html.append("</p>");

            html.append("<br/><div><font color='gray' size='3' face='Arial'>");
            html.append(dict.getDictionaryDescription().replaceAll("[\\\\]par", "\n"));
            html.append("</font><div>");



        } catch (Exception e) {
            wl.util.Utils.printToLog("Error al mostrar el diccionario: " + dictid, e, Preferences.LOG_LEVEL_ERROR);
        }

        html.append("</body>\n");
        html.append("</html>\n");
        return html.toString();
    }

    public static String getDictionaryRootMenu() throws IOException{
        List<IDictionary> dicts = DictionaryUtils.getDictionaries();
        StringBuilder html = new StringBuilder();
        html.append("<html>\n");
        html.append("<head></head>\n");
        html.append("<body>\n");
        html.append("<p><font size='6' color='green' face='Arial'>");
        html.append(dicts.size());
        html.append(" ");
        html.append(TextResourcesUtil.getText("diccionarios"));
        html.append("</font></p>");
        for (IDictionary d : dicts) {
            try{
            html.append("<div style='width:100%;padding:5px;background-color:lightgray;border-style:solid;border-color:green;border-width:1px'>");
            html.append("<a style='text-decoration:none' href='");
            html.append("dictionary:");
            html.append(d.getDictionaryId());
            html.append("&null'>");
            html.append("<font size='4' color='gray' face='Arial'><b>");
            html.append(d.getDictionaryName());
            html.append("</b></font>");
            html.append("</a><br/>");
            if(d.getDictionaryUrl()!=null){
                html.append("<font size='2' color='lightgray' face='Arial'>");
                html.append(d.getDictionaryUrl());
                html.append("</font><br>");
            }
            html.append(d.getAllWords().size());
            html.append(" ");
            html.append(TextResourcesUtil.getText("definiciones"));
            html.append("</div><br/>");
            }catch(Exception e){
                wl.util.Utils.printToLog("Error al mostrar el diccionario: "+d.getDictionaryId(), e, Preferences.LOG_LEVEL_ERROR);
            }
        }

        html.append("</body>\n");
        html.append("</html>\n");
        return html.toString();
    }



}
